package com.tl.commonlibrary.tool;

import android.view.View;

/**
 * Created by Administrator on 2017/6/8 0008.
 */

public class CountDownTimer {
    private long totalTime = 60 * 1000;
    private long countDownInterval = 1000;
    private android.os.CountDownTimer timer;
    private OnCountDownListener listener;
    private boolean isTimering = false;
    private View attachView;
    private int count = 0;//验证码验证次数
    private int type;
    public CountDownTimer() {
        init();
    }

    public CountDownTimer(long totalTime) {
        this.totalTime = totalTime;
        init();
    }

    public CountDownTimer(long totalTime, long countDownInterval) {
        this.totalTime = totalTime;
        this.countDownInterval = countDownInterval;
        init();
    }

    public void setAttachView(View attachView) {
        this.attachView = attachView;
    }

    private void init() {
        timer = new android.os.CountDownTimer(totalTime, countDownInterval) {
            @Override
            public void onTick(long millisUntilFinished) {
                isTimering = true;
                if (attachView != null) {
                    attachView.setEnabled(false);
                }
                if (listener != null) {
                    listener.onTick(millisUntilFinished);
                }
            }

            @Override
            public void onFinish() {
                isTimering = false;
                if (attachView != null) {
                    attachView.setEnabled(true);
                }
                if (listener != null) {
                    listener.onFinish();
                }
            }
        };
    }

    public void start() {
        if (!isTimering) {
            count++;
            timer.start();
        }
    }
    public boolean isTimering(){
        return isTimering;
    }
    public boolean isStarted() {
        return count > 0;
    }
    public int getCount(){
        return count;
    }

    public int getType() {
        return type;
    }

    public void setType(int type) {
        this.type = type;
    }

    public void cancel() {
        timer.cancel();
    }

    public void setOnCountDownListener(OnCountDownListener listener) {
        this.listener = listener;
    }

    public interface OnCountDownListener {
        void onTick(long millisUntilFinished);

        void onFinish();
    }

}
